﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordNet.Core.ElementContracts;

namespace WordNet.Core
{
    public class ExceptionEntryID: IExceptionEntryID
    {
        private readonly String _surfaceForm;
        private readonly POS _pos;

        public ExceptionEntryID(String surfaceForm, POS pos)
        {
            if (pos == null)
                throw new ArgumentNullException();
            if (surfaceForm == null)
                throw new ArgumentNullException();
            surfaceForm = surfaceForm.Trim();
            if (surfaceForm.Length == 0)
                throw new ArgumentException();
            // all exception entries are lower-case
            // this call also checks for null
            _surfaceForm = surfaceForm.ToLower();
            _pos = pos;
        }
       
        public string SurfaceForm
        {
            get { return _surfaceForm; }
        }

        public POS PartOfSpeech
        {
            get { return _pos; }
        }

        public override string ToString()
        {
            return String.Format("EID-{0}-{1}", _surfaceForm, _pos.Tag);
        }

        public override int GetHashCode()
        {
            const int PRIME = 31;
            int result = 1;
            result = PRIME * result + _surfaceForm.GetHashCode();
            result = PRIME * result + _pos.GetHashCode();
            return result;
        }

        public override bool Equals(object obj)
        {
            if (Object.ReferenceEquals(obj, null))
                return false;
            if (Object.ReferenceEquals(this, obj))
                return true;
            IExceptionEntryID other = obj as IExceptionEntryID;
            if (other == null)
                return false;
           
            if (!_surfaceForm.Equals(other.SurfaceForm))
                return false;
            if (!_pos.Equals(other.PartOfSpeech))
                return false;
            return true;
        }
       
        public static ExceptionEntryID ParseExceptionEntryID(String value)
        {
            if (value == null)
                throw new ArgumentNullException();

            if (!value.StartsWith("EID-"))
                throw new ArgumentException();

            if (value[value.Length - 2] != '-')
                throw new ArgumentException();

            POS pos = POS.GetPartOfSpeech(value[value.Length - 1]);

            return new ExceptionEntryID(value.Substring(4, value.Length - 2), pos);
        }
    }
}
